// pages/panicBuy/panicBuy.js
import {
  getSecKill,
  killGoods
} from '../../api/seckill'
import {
  addCart
} from '../../api/cart'
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    statusBarHeight: '',
    titleBarHeight: '',
    timeList: [],
    isIndex: 0
  },
  back() {
    wx.navigateBack({
      delta: 1
    })
  },

  tapTime(e) {
    let isIndex = e.currentTarget.dataset.index
    this.setData({
      isIndex
    })
  },

  async getData() {
    let res = await getSecKill(wx.getStorageSync('access_token'))
    console.log(res)
    this.setData({
      timeList: res.data
    })
    for (let i = 0; i < this.data.timeList.length; i++) {
      if (this.data.timeList[i].distanceStartTime == 0) {
        this.setData({
          isIndex: i
        })
      }
    }
  },

  async buy(e) {
    console.log(e)
    if (e.currentTarget.dataset.stock < 1) {
      wx.showToast({
        title: '手慢了，商品已被抢光',
        icon: 'none'
      })
      return
    }
    let kill = await killGoods(e.currentTarget.dataset.seckillid, e.currentTarget.dataset.skuid, wx.getStorageSync('access_token'))
    if ( kill && kill.success ) {
      let cartData = {
        skuId: e.currentTarget.dataset.skuid,
        num: 1,
        cartType: 'SECKILL'
      }
      let res = await addCart(cartData, wx.getStorageSync('access_token'))
      if (res && res.code == 10000) {
        wx.redirectTo({
          url: "/pages/pay-order/pay-order?orderType=SECKILL"
        })
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    } else {
      wx.showToast({
        title: kill.msg,
        icon: 'none'
      })
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      statusBarHeight: app.globalData.statusBarHeight,
      titleBarHeight: app.globalData.titleBarHeight
    })
    if (app.globalData.iphone == true) {
      that.setData({
        iphone: 'iphone'
      })
    }
    wx.hideShareMenu()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getData()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})